import { AccessKey, HuobiUrlPrex, SecretKey } from "../Config";
const CryptoJS = require('crypto-js');
const moment = require('moment');
const HmacSHA256 = require('crypto-js/hmac-sha256')
import url = require('url');

export default class Helper {
    static sign_sha(method, baseurl, path, data) {
        let pars = [];
        for (let item in data) {
            pars.push(item + "=" + encodeURIComponent(data[item]));
        }
        let p = pars.sort().join("&");
        let meta = [method, baseurl, path, p].join('\n');
        let hash = HmacSHA256(meta, SecretKey);
        let Signature = encodeURIComponent(CryptoJS.enc.Base64.stringify(hash));
        p += `&Signature=${Signature}`;
        return p;
    }

    static get_body() {
        return {
            AccessKeyId: AccessKey,
            SignatureMethod: "HmacSHA256",
            SignatureVersion: 2,
            Timestamp: moment.utc().format('YYYY-MM-DDTHH:mm:ss'),
        };
    }

    static prePost(post_context_path: string, post_body?: any) {
        post_body = post_body || {};
        let post_path = HuobiUrlPrex + post_context_path;
        let host = url.parse(post_path).host;
        let cpath = url.parse(post_path).path;
        let body = Object.assign(Helper.get_body(), post_body);
        let payload = Helper.sign_sha('POST', host, cpath, body);
        let post_url = `${post_path}?${payload}`
        return {
            body: body,
            post_url: post_url
        }
    }
    /**
     * 访问账户相关的接口需要进行签名认证。
     */
    static preGet(post_context_path: string, post_body?: any) {
        post_body = post_body || {};
        let get_path = HuobiUrlPrex + post_context_path;
        let host = url.parse(get_path).host;
        let cpath = url.parse(get_path).path;
        let body = Object.assign(Helper.get_body(), post_body);
        let payload = Helper.sign_sha('GET', host, cpath, body);
        return `${get_path}?${payload}`
    }
}